package com.zhazha.earlybird.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.zhazha.earlybird.beans.CompetitionInfo;

public class CompetitionDAO {
	
	private SQLiteDatabase mDatabase;
	
	private static final String COMPETITION_TABLE = "competition";
	
	private static final String COMPETITION_ID = "id"; 
	private static final String COMPETITION_TITLE = "title";
	private static final String COMPETITION_KIND_ID = "kind_id";
	private static final String COMPETITION_HIT_COUNT = "hit_count";
	
	public CompetitionDAO(SQLiteDatabase datebase) {
		this.mDatabase = datebase;
	}
	
	public CompetitionInfo[] queryAll() {
		CompetitionInfo[] info = null;
		
		try {
			
			 Cursor c = this.mDatabase.query(COMPETITION_TABLE, null, null, null, null, null, "id asc");
			
			if(c.moveToFirst()) {
				info = new CompetitionInfo[c.getCount()];
				for (int i = 0; i < c.getCount(); i++) {
					
					info[i] = new CompetitionInfo();
					info[i].setId(c.getInt(c.getColumnIndex(COMPETITION_ID)));
					info[i].setTitle(c.getString(c.getColumnIndex(COMPETITION_TITLE)));
					info[i].setKindId(c.getInt(c.getColumnIndex(COMPETITION_KIND_ID)));
					info[i].setHitCount(c.getInt(c.getColumnIndex(COMPETITION_HIT_COUNT)));

					c.moveToNext();
				}
				return info;
				
			}
			
			return info;
		}
		catch (Exception e) {
			e.printStackTrace();
			return info;
		}
	}
	
	public void deleteAll() {
		
		try{
			this.mDatabase.delete(COMPETITION_TABLE, null, null);
		}
		catch( Exception e) {
			e.printStackTrace();
		}
	}
	
	public void insert(CompetitionInfo[] info) {
		
		try{
			for(int i = 0; i < info.length; i++) {
				
				ContentValues cv = new ContentValues();
				cv.put(COMPETITION_ID, info[i].getId());
				cv.put(COMPETITION_TITLE, info[i].getTitle());
				cv.put(COMPETITION_KIND_ID, info[i].getKindId());
				cv.put(COMPETITION_HIT_COUNT, info[i].getHitCount());

				this.mDatabase.insert(COMPETITION_TABLE, null, cv);
			}
		}
		catch( Exception e){
			e.printStackTrace();
		}
	}

}
